//
//  ColumnBar.m
//  LearnObjectiveC
//
//  Created by 吴可高 on 16/6/6.
//  Copyright © 2016年 吴可高. All rights reserved.
//

#import "ColumnBar.h"
#import "BrokenPointValue.h"

@implementation ColumnBar

-(void)drawRect:(CGRect)rect
{

    [super drawRect:rect];
    [self.items enumerateObjectsUsingBlock:^(BrokenPointValue * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self drawColumeBar:idx brokenPointValue:obj];
    }];
}

-(void)drawColumeBar:(NSUInteger)i brokenPointValue:(BrokenPointValue*)value
{
    BrokenShapeLayer * barlayer = [BrokenShapeLayer layer];
    barlayer.lineCap = kCALineCapButt;
    barlayer.lineWidth = self.barWidth;
    barlayer.fillColor = [self convertColor:value.pointColor].CGColor;
    barlayer.strokeColor = [self convertColor:value.pointColor].CGColor;
    
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, &CGAffineTransformIdentity, kMargin_Left  + (i + 1) * self.xDistance, [self getFrameY:0]);
    CGPathAddLineToPoint(path, &CGAffineTransformIdentity, kMargin_Left + (i + 1) * self.xDistance, [self getFrameY:value.pointY]);
    
    barlayer.path = path;
    [self.layer addSublayer:barlayer];
    CGPathRelease(path);
    
    if (self.isAnimated) {
        [barlayer addAnimationKeyPath:@"strokeEnd" fromValue:@(0) toValue:@(1) duration:self.timeInterval delegate:self];
    }
}

- (UIColor *)convertColor:(UIColor *)color {
    if (color != [UIColor whiteColor] && color != [UIColor clearColor] && color != nil) {
        return color;
    }
    return self.backgroundColor;
}

-(CGFloat)barWidth
{
    return _barWidth ==0 ? 12 : _barWidth;
}

-(void)animationDidStart:(CAAnimation *)anim
{
    
}
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
}
@end
